#include <signal.h>
#include <iostream>
#include <string>
#include <thread>
#include <chrono>

#include "example.srpc.h"
#include "workflow/WFFacilities.h"

using namespace srpc;
using std::string;

static WFFacilities::WaitGroup waitGroup{ 1 };

void sighandler(int)
{
	waitGroup.done();
}

class ExampleServiceImpl : public Example::Service
{
public:
	void Echo(EchoRequest *request, EchoResponse *response, srpc::RPCContext *ctx) override
	{
        // 1. 解析客户端的请求参数
        const string& message = request->message(); // getter
        const string& name = request->name();
        std::cout << "Request: { message=" << message
            << ", name=" << name << " }\n";

        // 2. 服务端的业务逻辑
        using namespace std;
        this_thread::sleep_for(chrono::seconds{3});
        // 3. 生成响应，并返回
        response->set_message("Hi, " + name);   // setter
	}
};

int main()
{
    // 注册信号处理函数
    signal(SIGINT, sighandler);

	SRPCServer server;

    // 添加服务
	ExampleServiceImpl service;
	server.add_service(&service);

    if (server.start(9527) == 0) {
        waitGroup.wait();
        server.stop();
    } else {
        std::cerr << "Error: start server failed!\n";
        std::exit(1);
    }

	return 0;
}
